package org.znxs.comfriend.fragments;

import static androidx.constraintlayout.helper.widget.MotionEffect.TAG;
import static org.znxs.comfriend.utils.UserUtils.IMAGE_URLS;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;

import org.znxs.comfriend.R;
import org.znxs.comfriend.activities.LoginActivity;
import org.znxs.comfriend.activities.ProfilePreviewActivity;
import org.znxs.comfriend.models.User;
import org.znxs.comfriend.utils.LoginUser;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

public class ProfileFragment extends Fragment {

    private View loggedInView;
    private View notLoggedInView;

    private ImageView ivAvatar;
    private TextView tvNickname;
    private TextView tvBio;
    private RadioGroup rgGender;
    private RadioButton rbMale;
    private RadioButton rbFemale;

    private LinearLayout imagePreviewContainer;

    private LoginUser loginUser;

    private static final int PICK_IMAGE_REQUEST = 100; // 请求码


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_profile, container, false);

        // 初始化
        loginUser = LoginUser.getInstance(getContext());

        // 初始化视图
        loggedInView = view.findViewById(R.id.logged_in_layout);
        notLoggedInView = view.findViewById(R.id.not_logged_in_layout);

        ivAvatar = view.findViewById(R.id.iv_avatar);
        tvNickname = view.findViewById(R.id.tv_nickname);
        tvBio = view.findViewById(R.id.tv_bio);
        rgGender = view.findViewById(R.id.rg_gender);
        rbMale = view.findViewById(R.id.rb_male);
        rbFemale = view.findViewById(R.id.rb_female);

        Button btnLogout = view.findViewById(R.id.btn_logout);
        Button btnLogin = view.findViewById(R.id.btn_login);

        // 图片预览容器
        imagePreviewContainer = view.findViewById(R.id.image_preview_container);

        // 设置点击事件
        ivAvatar.setOnClickListener(v -> changeAvatar());
        view.findViewById(R.id.layout_nickname).setOnClickListener(v -> editInfo("nickname", "修改昵称", tvNickname));
        view.findViewById(R.id.layout_bio).setOnClickListener(v -> editInfo("bio", "修改个人简介", tvBio));

        // 性别选择监听
        rgGender.setOnCheckedChangeListener((group, checkedId) -> {
            String gender = checkedId == R.id.rb_male ? "男" : "女";
            User currentUser = loginUser.getLoginUser();
            if (currentUser != null) {
                currentUser.setGender(gender);
                loginUser.setLoginUser(currentUser); // 持久化保存用户信息
            }
        });

        btnLogout.setOnClickListener(v -> logout());
        btnLogin.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            intent.putExtra("from_profile", true);
            startActivity(intent);
            requireActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
        });

        checkLoginStatus();

        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == getActivity().RESULT_OK && data != null) {
            Uri selectedImageUri = data.getData();

            if (selectedImageUri != null) {
                User currentUser = loginUser.getLoginUser();
                if (currentUser == null) return;

                String oldAvatarPath = currentUser.getAvatarUrl(); // 获取旧头像路径

                // 删除旧头像文件
                deleteOldAvatar(oldAvatarPath);

                // 保存新头像到本地存储并获取新路径
                String newAvatarPath = saveImageToInternalStorage(selectedImageUri);
                if (newAvatarPath == null) {
                    Toast.makeText(getContext(), "保存头像失败", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 更新用户信息中的头像路径
                currentUser.setAvatarUrl(newAvatarPath);
                loginUser.setLoginUser(currentUser); // 持久化保存用户信息

                // 使用 Glide 渲染新头像
                Glide.with(requireContext())
                        .load(selectedImageUri)
                        .placeholder(R.drawable.pengyiyan) // 占位图
                        .error(R.drawable.error) // 错误时显示的图片
                        .into(ivAvatar);
            }
        }
    }

    private String saveImageToInternalStorage(Uri uri) {
        try {
            Context context = requireContext();
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            if (inputStream == null) return null;

            File file = new File(context.getFilesDir(), "avatar.png");
            FileOutputStream outputStream = new FileOutputStream(file);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }

            outputStream.close();
            inputStream.close();

            return file.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private void deleteOldAvatar(String oldPath) {
        if (oldPath == null || oldPath.isEmpty() || oldPath.equals("default")) return;

        File oldFile = new File(oldPath);
        if (oldFile.exists()) {
            oldFile.delete();
        }
    }
    private void loadUserData() {
        User currentUser = loginUser.getLoginUser();
        if (currentUser == null) return;

        tvNickname.setText(currentUser.getNickname());
        tvBio.setText(currentUser.getBio());

        // 设置性别选择
        if ("男".equals(currentUser.getGender())) {
            rbMale.setChecked(true);
        } else {
            rbFemale.setChecked(true);
        }

        // 默认头像
        if("".equals(currentUser.getAvatarUrl())){
        Log.d(TAG, "loadUserData: "+currentUser.getAvatarUrl());
            ivAvatar.setImageResource(R.drawable.pengyiyan);
        }else{
            // 使用 Glide 渲染新头像
            Glide.with(requireContext())
                    .load(currentUser.getAvatarUrl())
                    .placeholder(R.drawable.pengyiyan) // 占位图
                    .error(R.drawable.pengyiyan) // 错误时显示的图片
                    .into(ivAvatar);
        }

        // 加载默认图片列表
        loadDefaultImages();
    }

    private void changeAvatar() {
        // 打开相册选择图片
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*"); // 选择图片类型
        startActivityForResult(intent, PICK_IMAGE_REQUEST); // 启动图片选择
    }

    private void loadDefaultImages() {
        // 模拟默认图片列表 todo 需要切换到具体列表
        List<String> defaultImages = loginUser.getLoginUser().getImages();

        // 清空之前的图片
        imagePreviewContainer.removeAllViews();

        for (String imageResUrl : defaultImages) {
            ImageView imageView = new ImageView(requireContext());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    getResources().getDimensionPixelSize(R.dimen.image_preview_size),
                    getResources().getDimensionPixelSize(R.dimen.image_preview_size)
            );
            params.setMargins(
                    getResources().getDimensionPixelSize(R.dimen.image_preview_margin),
                    0,
                    0,
                    0
            );
            imageView.setLayoutParams(params);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

            // 使用 Glide 加载图片
            Glide.with(requireContext())
                    .load(imageResUrl) // 图片的 URL
                    .placeholder(R.drawable.pengyiyan) // 占位图（可选）
                    .error(R.drawable.error) // 错误时显示的图片（可选）
                    .into(imageView);

            // 点击事件中调用
            imageView.setOnClickListener(v -> openImageDetails());

            // 将 ImageView 添加到容器中
            imagePreviewContainer.addView(imageView);
        }
    }



    private void editInfo(String key, String title, TextView textView) {
        new AlertDialog.Builder(requireContext())
                .setTitle(title)
                .setView(R.layout.dialog_edit_text)
                .setPositiveButton("确定", (dialog, which) -> {
                    AlertDialog d = (AlertDialog) dialog;
                    EditText etInput = d.findViewById(R.id.et_input);
                    if (etInput != null) {
                        String newValue = etInput.getText().toString();
                        textView.setText(newValue);

                        // 更新用户信息
                        User currentUser = loginUser.getLoginUser();
                        if (currentUser != null) {
                            switch (key) {
                                case "nickname":
                                    currentUser.setNickname(newValue);
                                    break;
                                case "bio":
                                    currentUser.setBio(newValue);
                                    break;
                            }
                            loginUser.setLoginUser(currentUser); // 持久化保存用户信息
                        }
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void logout() {
        new AlertDialog.Builder(requireContext())
                .setTitle("确认退出")
                .setMessage("确定要退出登录吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    // 清除登录状态
                    loginUser.clearLoginUser();

                    // 跳转到登录页面
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                    requireActivity().finish();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void checkLoginStatus() {
        User currentUser = loginUser.getLoginUser();
        Log.d(TAG, "checkLoginStatus: "+currentUser);
        if (currentUser != null) {
            showLoggedInUI();
            loadUserData();
        } else {
            showNotLoggedInUI();
        }
    }

    // 显示已登录UI
    private void showLoggedInUI() {
        if (loggedInView != null) loggedInView.setVisibility(View.VISIBLE);
        if (notLoggedInView != null) notLoggedInView.setVisibility(View.GONE);
    }

    // 显示未登录UI
    private void showNotLoggedInUI() {
        if (loggedInView != null) loggedInView.setVisibility(View.GONE);
        if (notLoggedInView != null) notLoggedInView.setVisibility(View.VISIBLE);
    }

    // 打开图片详情页
    private void openImageDetails() {
        Intent intent = new Intent(requireContext(), ProfilePreviewActivity.class);
        intent.putExtra("user", loginUser.getLoginUser());
        startActivity(intent);
    }
}